package com.jun.rabbitmq.consumer.config;

import com.jun.common.rabbitmq.constant.ExchangeConstant;
import com.jun.common.rabbitmq.constant.QueueConstant;
import com.jun.common.rabbitmq.constant.RouteConstant;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author yuejun.li
 * @date 2024/4/24 11:39:50
 */
@Configuration
@ConditionalOnProperty(name = "spring.rabbitmq.listener.simple.retry.enabled", havingValue = "true")
public class ErrorMessageConfig {

    @Bean
    public DirectExchange errorMessageExchange(){
        return new DirectExchange(ExchangeConstant.ERROR_DIRECT_EXCHANGE,true,false);
    }
    @Bean
    public Queue errorQueue(){
        return new Queue(QueueConstant.ERROR_QUEUE, true);
    }

    @Bean
    public Binding errorBinding(Queue errorQueue, DirectExchange errorMessageExchange){
        return BindingBuilder.bind(errorQueue).to(errorMessageExchange).with(RouteConstant.ERROR_KEY);
    }

    @Bean
    public MessageRecoverer republishMessageRecoverer(RabbitTemplate rabbitTemplate){
        return new RepublishMessageRecoverer(rabbitTemplate, ExchangeConstant.ERROR_DIRECT_EXCHANGE, RouteConstant.ERROR_KEY);
    }
}
